package light.head.dao.oa;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import light.head.cache.Cache;
import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.model.DocumentType;


@Service
public class DocumentTypeDAO extends BaseDAO<DocumentType, Integer>{

	private final static String sql_findAll = "FROM DocumentType dt WHERE dt.oc = ?";
	private final static String sql_loadAll = "FROM DocumentType";

	public RESULT findByMap(Map<String, String> map, PageBean pageBean) {
		StringBuffer hql = new StringBuffer("FROM DocumentType dt WHERE 1 = 1");
		
		List<Object> list = null;
		if (map != null) {
			list = new ArrayList<Object>();
			String oc = map.get(Parm.OC);
			String name = map.get(Parm.NAME);
			if (null != name && !"".equals(name)) {
				hql.append(" AND dt.name LIKE ?");
				list.add("%" + name + "%");
			}if(isNotNull(oc)){
				hql.append(" AND dt.oc = ?");
				list.add(Integer.parseInt(oc));
			}
		}
		
		hql.append(" ORDER BY dt.code DESC");
		
		if (findToPageBean(hql.toString(), pageBean, list) == RESULT.SUCCESS)
			return RESULT.SUCCESS;
		return RESULT.ERROR;
	}
	/**
	 * 修改文档类别信息
	 */
	public RESULT update(DocumentType documentType) {
		if (null == documentType || null == documentType.getCode())
			return RESULT.PARAMETER_ERROR;
		
		DocumentType old = get(documentType.getCode());
		if (null == old)
			return RESULT.NOT_FIND;
		if(null !=(documentType.getName())) {
			old.setName(documentType.getName());
		}
		if (RESULT.SUCCESS == upd(old)) {
			this.loadAll();
			return RESULT.SUCCESS;
		} else {
			return RESULT.ERROR;
		}
	}
	
	/**
	 * 
	 * @param oc
	 * @return
	 */
	public List<DocumentType> findAll(String oc) {
		List<DocumentType> list = find(sql_findAll, Integer.parseInt(oc));
		return list;
	}
	
	/**
	 * 
	 * @param oc
	 * @return
	 */
	public List<DocumentType> findAllByOc(Integer oc) {
		List<DocumentType> list = find(sql_findAll, oc);
		return list;
	}
	
	public List<DocumentType> loadAll() {
		Cache.documentTypeList = find(sql_loadAll);
		return Cache.documentTypeList;
	}
	public List<DocumentType> findByNameOc(String name, Integer oc){
		if (name == null || oc == null) return null;
		StringBuffer hql = new StringBuffer("FROM DocumentType iat WHERE iat.name = ? AND iat.oc = ? ");
		List<Object> parm = new ArrayList<Object>();
		
		parm.add(name);
		parm.add(oc);
		
		return find(hql.toString(), parm.toArray());
	}
}
